<script setup lang="ts">
import { addSystemEmpAPI, deleteSystemEmpAPI, editSystemEmpAPI, getSystemEmpDataAPI, resetPasswordAPI } from '@/apis/systemEmp';
import { getRoleListAPI } from '@/apis/systemRole';
import { type addSystemEmpParamsType, type SystemEmpItemType, type SystemEmpListParamsType } from '@/types/systemEmp';
import type { RoleItemType } from '@/types/systemRole';
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus';
import { ref, watch } from 'vue';


// 列表参数
const systemEmpParams = ref<SystemEmpListParamsType>({
  page: 1,
  pageSize: 5,
  name: undefined
})

// 获取员工数据
const systemEmpList = ref<SystemEmpItemType[]>([]) // 员工列表
const systemEmpTotal = ref(0) // 员工总数
const getSystemEmpData = async () => {
  const res = await getSystemEmpDataAPI(systemEmpParams.value)
  systemEmpList.value = res.data.rows
  systemEmpTotal.value = res.data.total
}
getSystemEmpData()

const addFormRef = ref<FormInstance>() // 表单实例

// 弹窗 ----------------
const dialogVisible = ref(false) // 弹窗控制

// open
const empId = ref<number | undefined>()
const openDialog = async (row?: SystemEmpItemType) => {
  await getRoleList() // 获取角色下拉框信息

  // 编辑回显数据
  if (row) {
    addSystemEmpParams.value.name = row.name
    addSystemEmpParams.value.phonenumber = row.phonenumber
    addSystemEmpParams.value.roleId = row.roleId
    addSystemEmpParams.value.userName = row.userName
    addSystemEmpParams.value.status = row.status
    addSystemEmpParams.value.roleName = row.roleName
    empId.value = row.id
  }

  dialogVisible.value = true
}

// close
const closeDialog = () => {
  dialogVisible.value = false // 关闭弹窗

  // 重置表单
  addFormRef.value?.resetFields()
  empId.value = undefined
  addSystemEmpParams.value = {
    name: '',
    phonenumber: '',
    roleId: undefined,
    roleName: undefined,
    status: undefined,
    userName: ''
  }
}

// 获取角色下拉框列表
const roleList = ref<RoleItemType[]>([])
const getRoleList = async () => {
  const res = await getRoleListAPI()
  roleList.value = res.data
}

// 弹窗表单数据
const addSystemEmpParams = ref<addSystemEmpParamsType>({
  name: '', // 员工姓名
  // password: '123456', // 默认密码 // 可恶啊，不能传
  userName: '', // 登录账号
  phonenumber: '', // 联系方式
  roleName: undefined, // 角色名称
  status: undefined, // 状态
  roleId: undefined, // 角色id
})

// 收集角色下拉框数据
watch(() => addSystemEmpParams.value.roleId, (newValue) => {
  if (newValue) {
    addSystemEmpParams.value.roleName = roleList.value.find(item => +item.roleId === newValue)?.roleName
  } else {
    addSystemEmpParams.value.roleName = undefined
  }
})

// 表单校验
const addSystemEmpRules = ref<FormRules<addSystemEmpParamsType>>({
  name: [
    { required: true, message: '请输入员工姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  phonenumber: [
    { required: true, message: '请输入联系方式', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  roleId: [
    { required: true, message: '请选择分配角色', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  userName: [
    { required: true, message: '请输入登录账号', trigger: 'blur' },
    { min: 2, max: 12, message: '长度在 2 到 12 个字符', trigger: 'blur' }
  ]
})

// 提交表单
const loadingFlag = ref(false) // 加载中
const submitForm = async () => {
  await addFormRef.value?.validate() // 校验表单
  loadingFlag.value = true

  try {
    if (!empId.value) {
      // 添加
      await addSystemEmpAPI(addSystemEmpParams.value)
      ElMessage.success('添加成功')
    } else {
      // 编辑
      const res = await editSystemEmpAPI({
        ...addSystemEmpParams.value,
        id: empId.value
      })
      // 提示
      if (res.code === 10000) {
        ElMessage.success('编辑成功')
      } else {
        ElMessage.error(res.msg)
      }
    }

    closeDialog() // 关闭弹窗
    getSystemEmpData() // 刷新表格数据
  } finally {
    loadingFlag.value = false
  }
}

// 删除员工
const deleteEmp = async (id: number) => {
  await ElMessageBox.confirm('确定删除吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })

  const res = await deleteSystemEmpAPI(id) // 删除员工
  if (res.code === 10000) {
    ElMessage.success('删除成功')
  } else {
    ElMessage.error(res.msg)
  }

  getSystemEmpData()
}

// 重置密码
const resetPassword = async (id: number) => {
  await ElMessageBox.confirm('确定将密码重置为"123456"吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })

  const res = await resetPasswordAPI(id) // 重置密码
  if (res.code === 10000) {
    ElMessage.success('重置成功')
  } else {
    ElMessage.error(res.msg)
  }
}

</script>

<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">员工姓名：</div>
      <el-input clearable placeholder="请输入员工姓名" v-model="systemEmpParams.name" @clear="getSystemEmpData()" class="search-main" />
      <el-button type="primary" @click="getSystemEmpData()">查询</el-button>
    </div>
    <div class="create-container">
      <el-button type="primary" @click="openDialog()" v-permission="'sys:user:add_edit'">添加员工</el-button>
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="systemEmpList">
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column label="员工姓名" prop="name" />
        <el-table-column label="登录账号" prop="userName" />
        <el-table-column label="联系方式" prop="phonenumber" />
        <el-table-column label="角色" prop="roleName" />
        <el-table-column label="状态">
          <template #default="{ row }">
            <el-tag type="success" v-if="row.status === 1">启用</el-tag>
            <el-tag type="warning" v-else>未启用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="添加时间" prop="createTime" width="200" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" type="primary" link @click="openDialog(scope.row)" v-permission="'sys:user:add_edit'">编辑</el-button>
            <el-button size="small" type="primary" link @click="deleteEmp(scope.row.id)" v-permission="'sys:user:remove'">删除</el-button>
            <el-button size="small" type="primary" link @click="resetPassword(scope.row.id)" v-permission="'ssys:user:resetPwd'">重置密码</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页区域 -->
    <div class="page-container">
      <el-pagination 
        layout="total, sizes, prev, pager, next"
        :total="systemEmpTotal" 
        :page-sizes="[2,5,10,20]"
        v-model:current-page="systemEmpParams.page"
        v-model:page-size="systemEmpParams.pageSize"
        @change="getSystemEmpData()"
      />
    </div>
    <!-- 弹窗 -->
    <el-dialog v-model="dialogVisible" @close="closeDialog()" :title="!empId ? '添加员工' : '编辑员工'" width="580px">
      <div class="form-container">
        <!-- 表单区域 -->
        <el-form :model="addSystemEmpParams" :rules="addSystemEmpRules" ref="addFormRef" label-position="top">
          {{ addSystemEmpParams }}{{ empId }}
          <el-form-item label="员工姓名" prop="name">
            <el-input placeholder="请填写员工姓名" v-model="addSystemEmpParams.name"></el-input>
          </el-form-item>
          <el-form-item label="登录账号" prop="userName">
            <el-input placeholder="请填写登录账号" v-model="addSystemEmpParams.userName" ></el-input>
          </el-form-item>
          <el-form-item label="联系方式" prop="phonenumber">
            <el-input placeholder="请填写联系方式" v-model="addSystemEmpParams.phonenumber"></el-input>
          </el-form-item>

          <el-form-item>
            <div class="def-pwd"><span>默认密码：</span><span>123456</span></div>
          </el-form-item>

          <el-form-item label="分配角色" prop="roleId">
            <el-select placeholder="请选择分配角色" v-model="addSystemEmpParams.roleId" clearable>
              <el-option
                v-for="item in roleList"
                :key="item.roleId"
                :label="item.roleName"
                :value="item.roleId"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="员工状态" prop="status">
            <el-radio-group v-model="addSystemEmpParams.status">
              <el-radio :value="0" size="large">禁用</el-radio>
              <el-radio :value="1" size="large">启用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="closeDialog()">取 消</el-button>
        <el-button type="primary" @click="submitForm()" :loading="loadingFlag">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.ping-fang {
  display: flex;
  width: 100%;
  span {
    padding: 0 5px;
    border: 1px solid #e0e0e0;
    font-size: 12px;
    background-color: #fafafa;
  }
}
.son-table {
  // background-color: #f4f6f8;
  margin-left: 47px;
}
.building-container {
  padding: 20px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, .9);
  ;
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}
</style>
